package cn.xuqiudong.blog.module.third.controller;

import cn.xuqiudong.blog.base.BaseBlogController;
import cn.xuqiudong.blog.constant.ThirdProperties;
import cn.xuqiudong.blog.module.third.service.OauthFacade;
import cn.xuqiudong.blog.module.third.service.impl.GiteeAuthService;
import cn.xuqiudong.blog.module.third.service.impl.GithubAuthService;
import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.blog.model.BlogThirdUser;
import cn.xuqiudong.common.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 说明 :  第三方登录
 * @author Vic.xu
 * @since  2020/7/21 0021 17:41
 */
@Controller
@RequestMapping("/third")
public class ThirdLoginController extends BaseBlogController {

    @Autowired
    private GiteeAuthService giteeuthService;

    @Autowired
    private GithubAuthService githubAuthService;

    @Autowired
    private ThirdProperties thirdProperties;


    @Autowired
    private OauthFacade oauthFacade;

    /**
     * 前往第三方授权页面
     * @param type  第三方标志  如 gitee,github,qq等
     * @return url
     */
    @GetMapping(value = "/grant/{type}")
    public String toGrant(@PathVariable String type) {
        ThirdProperties.ThirdAuthConfig config = thirdProperties.getConfigByType(type);
        if (config == null) {
            throw new CommonException("不存在的授权方式");
        }
        if (StringUtils.isBlank(config.getRenderUrl())) {
            throw new CommonException("没有配置授权url");
        }
        return "redirect:" + config.getRenderUrl();
    }


    /**
     * 第三方登录回调地址
     * @param type 暂时支持gitee  github qq
     * @param code 授权码
     * @return 最后访问的地址
     */
    @RequestMapping("/callback/{type}")
    public Object callback(@PathVariable String type, String code) throws InterruptedException {
        logger.info("第三方{}登录回调, 参数{}", type, JsonUtil.toJson(request.getParameterMap()));
        try {
            BlogThirdUser user = oauthFacade.findUserInfoByCode(type, code);
            setSessionAttribute(PRINCIPAL_SESSION, user);
        } catch (Exception e) {
            logger.error(type + "类型的登录回调发生了一些错误", e);
        }

        return "redirect:" + lastUrl();
    }


    @GetMapping("/logout")
    public String logout() {
        setSessionAttribute(PRINCIPAL_SESSION, null);
        request.getSession().invalidate();
        return "redirect:/";
    }

}
